package com.chaos.gateway.config.filter;

import com.chaos.gateway.config.properties.ResourceserverProperties;
import com.chaos.gateway.helper.ResponseHelper;
import com.chaos.framework.model.constant.SecurityConstants;
import com.chaos.framework.model.enums.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;


/**
 * @author Jacky
 */
@Component
@Slf4j
public class GatewayActuatorFilter implements WebFilter {

    @Autowired
    private ResourceserverProperties resourceserverProperties;
    private final PathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        URI uri = request.getURI();
        String host = uri.getHost();

        if (!pathMatcher.match(SecurityConstants.ACTUATOR_MATCH, uri.getPath())) {
            return chain.filter(exchange);
        }

        List<String> hosts = resourceserverProperties.getActuatorHosts();

        if (hosts.contains(host)) {
            return chain.filter(exchange);
        }

        return ResponseHelper.writeErrorInfo(response, ResultEnum.FORBIDDEN);
    }

}
